package csc.fresher.view;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import csc.fresher.entity.SystemUser;
import csc.fresher.service.SystemUserService;

@Component
@Scope("request")
public class ManageAccountManageBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private SystemLoginManageBean systemLoginManageBean;

	@Autowired
	private SystemUserService systemUserService;

	
	public void onLoad() {
		SystemUser systemUser;

		if (systemLoginManageBean.getSystemUser() == null) {
			try {
				FacesContext.getCurrentInstance().getExternalContext()
						.redirect("/csc_final/templates3/Logon.jsf");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			systemUser = systemLoginManageBean.getSystemUser();
			List<Long> listrole = systemUserService
					.getRoleByUserName(systemUser.getUserName());
			boolean result = checkRole(listrole);
			if (result == false) {
				try {
					FacesContext.getCurrentInstance().getExternalContext()
							.redirect("AccountManagement.xhtml");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public boolean checkRole(List<Long> listRole) {

		for (int i = 0; i < listRole.size(); i++) {
			if (3 == listRole.get(i) || 4 == listRole.get(i)){
				return true;
			}
		}
		return false;
	}

}
